import axios from 'axios';
import { ElMessage } from 'element-plus';


const instance = axios.create({
  baseURL: 'http://192.168.89.2:8000/webApi',
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userData = JSON.parse(localStorage.getItem('userData'));
    const token = userData ? userData.token : null;

    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => response.data,
  (error) => {

    if (error.response) {
      switch (error.response.status) {
        case 401:
          ElMessage({
            message: "登录过期，请重新登录",
            type: 'error',
          });
           window.location.href = '/#/login'
          break;
        case 403:
          ElMessage({
            message: "没有权限访问该资源",
            type: 'error',
          });
          break;
        case 500:
          ElMessage({
            message: "服务器内部错误，请稍后重试",
            type: 'error',
          });
          break;
        default:
          ElMessage({
            message: error.response.data.message || "发生错误，请稍后重试",
            type: 'error',
          });
          break;
      }
    } else if (error.request) {
      ElMessage({
        message: "网络错误，请检查您的连接",
        type: 'error',
      });
    } else {
      ElMessage({
        message: "发生未知错误",
        type: 'error',
      });
    }
    return Promise.reject(error);
  }
);

export default instance;
